<!DOCTYPE HTML>
<html>
	<head>
		<meta charset="utf-8"/>
		<title>html选区</title>
		<style>
			span{
				display:inline-block;
				padding:4px 8px;
				cursor:default;
				border:1px solid #ccc;
				margin:4px;
			}
		</style>
	</head>
	<body>
		<div id="editor" contentEditable="true" style="height:50px; border:2px solid red;">asdfasdfasdfasd</div>
		<span onclick="restoredScene();">恢复选区</span>
		<span>取消选区</span>
		
		<script src="../../lib/jquery-1.8.3.min.js"></script>
		<script>
			var sel, rg, bkm;

			/*恢复选区现场*/
			function restoredScene() {
				if(rg){
					if(sel.addRange){
						sel.removeAllRanges();
						sel.addRange(rg);
					} else {
						rg.moveToBookmark(bkm);
	            		rg.select();
					}
					
					console.log(rg.parentElement);
					
					/*try{
						document.execCommand("inserthtml", false, '<a href="http://girlyuefang.com">女子十二乐坊</a>');
					} catch(e){
						try{
							rg.pasteHTML('<a href="http://girlyuefang.com">女子十二乐坊</a>');
						} catch(e){
							rg.deleteContents();
							rg.insertNode($('<a href="http://girlyuefang.com">女子十二乐坊</a>')[0]);
						}
					}*/
				}
			}
			
			/*保存选区现场*/
			$("#editor").on("mouseup keydown", function() {
				if(window.getSelection){
					sel = window.getSelection();
					rg = sel.getRangeAt(0).cloneRange();
				} else {
					sel = document.selection;
					rg = sel.createRange();
					bkm = rg.getBookmark();
				}
			});
		</script>
	</body>
</html>
